package czy.demo.service;

import czy.demo.common.constant.CacheName;
import czy.demo.entity.User;
import czy.demo.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/* 用户详情服务实现 */
@Primary
@Service
public class UserService implements UserDetailsService{

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepository;


    /* 根据用户名加载用户，被DaoAuthenticationProvider调用
     * 此方法进行缓存，键为id
     */
    @Override
    @Cacheable(value = CacheName.USER,key="#username")
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.debug("加载指定名称用户："+username);
        return this.userRepository.findByUsername(username);
    }

    /* 保存用户方法 */
    @CachePut(value = CacheName.USER,key="#user.username")
    public User save(User user){
        logger.debug("保存用户");
        return this.userRepository.save(user);
    }

    /* 清除用户缓存方法 */
    @CacheEvict(value = CacheName.USER,key = "#user.username",condition = "#user != null && #user.username != null")
    public void clearCache(User user){
        logger.debug("清除指定用户缓存："+user.getUsername());
    }
}
